/*
 * Copyright (c) 2006, 2022, webrx.cn All rights reserved.
 *
 */
package cn;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Parameter;
import java.util.Arrays;

/**
 * <p>Project: javase2203 - Reflection1
 * <p>Powered by webrx On 2022-08-11 11:18:10
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
public class Reflection1 {
    public static void main(String[] args) {
        //正射
        var s = new String("hello world");
        System.out.println("正射：" + s.toUpperCase());

        //反射操作
        var c = String.class;

        //只获取public方法
        //Method[] ms = c.getMethods();

        //获取所有方法，包括私有的，没有修饰的
        Method[] ms = c.getDeclaredMethods();
        Arrays.stream(ms).forEach(e -> {
            Parameter[] ps = e.getParameters();
            String ppss = Arrays.toString(ps);
            String pas = ps.length == 0 ? "" : ppss.substring(1, ppss.length() - 1);
            String rtype = e.getReturnType().getSimpleName();
            String modi = Modifier.toString(e.getModifiers());
            String mmm = String.format("%s%s %s(%s);", modi.length() == 0 ? modi : modi + " ", rtype, e.getName(), pas);
            System.out.println(mmm);
        });

        //反射执行java.lang.String类的toUpperCase()方法
        try {
            Class s2 = String.class;
            Constructor con = s2.getConstructor(String.class);
            Object ss = con.newInstance("hello world");
            Method m = s2.getMethod("toUpperCase");
            System.out.println("反射调用String.toUpperCase()方法:" + m.invoke(ss));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
